import { request } from '../../utils/request'
const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: '',
    fileList: [],
    fileListQr: [],
    avatarUrl: '',
    address: '',
    latitude: '',
    longitude: '',
    avatar: '',
    community: '',
    gender: '',
    groupLeaderShowPic: '',
    idCard: '',
    nickName: '',
    phone: '',
    realName: '',
    qrCode: '',
    from: '',
    size: {
      //裁剪尺寸
      width: 160,
      height: 240
    },
    cropSizePercent: 0.6, //裁剪框显示比例
    borderColor: '#fff' //裁剪框边框颜色
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let {
      address,
      latitude,
      longitude,
      avatar,
      community,
      gender,
      groupLeaderShowPic,
      idCard,
      nickName,
      phone,
      realName,
      qrCode
    } = JSON.parse(options.userInfo)
    this.setData({
      address: address,
      latitude: latitude,
      longitude: longitude,
      avatar: avatar,
      avatarUrl: avatar,
      community: community,
      gender: gender,
      groupLeaderShowPic: groupLeaderShowPic,
      qrCode: qrCode,
      idCard: idCard,
      nickName: nickName,
      phone: phone,
      realName: realName
    })
    if (this.data.groupLeaderShowPic.length > 0) {
      let fileList = [
        {
          url: this.data.groupLeaderShowPic,
          thumb: this.data.groupLeaderShowPic,
          status: 'success',
          isImage: true,
          name: 'img',
          id: '1',
          type: 'image'
        }
      ]
      this.setData({
        fileList: fileList
      })
    }
    if (this.data.qrCode.length > 0) {
      let fileListQr = [
        {
          url: this.data.qrCode,
          thumb: this.data.qrCode,
          status: 'success',
          isImage: true,
          name: 'img',
          id: '1',
          type: 'image'
        }
      ]
      this.setData({
        fileListQr: fileListQr
      })
    }
  },

  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    this.setData({
      avatarUrl: avatarUrl
    })
    const token = wx.getStorageSync('token')
    wx.uploadFile({
      url:
        'https://elf.byxfd.com' +
        '/mini/api/mine/updateAvatar',
      header: {
        'content-type': 'multipart/form-data',
        Authorization: token || ''
      },
      filePath: avatarUrl,
      name: 'avatar',
      success(res) {
        let data = res.data
        if (data) {
          data = JSON.parse(data)
        }
      },
      fail(err) {
        console.log(err)
      }
    })

    // wx.getFileSystemManager().readFile({
    //   filePath: avatarUrl, //要读取的文件的路径 (本地路径)
    //   encoding: 'base64', //指定读取文件的字符编码
    //   success(res) {
    //     //转换完毕，执行上传
    //     let avatar = encodeURI(
    //       'data:image/png;base64,' + res.data
    //     ).replace(/\+/g, '%2B')
    //   }
    // })
  },

  uploadImg(image) {
    var _this = this
    const token = wx.getStorageSync('token')
    wx.uploadFile({
      url:
        'https://elf.byxfd.com' +
        '/mini/api/file/upload',
      header: {
        'content-type': 'multipart/form-data',
        Authorization: token || ''
      },
      filePath: image,
      name: 'file',
      success(res) {
        let data = res.data
        if (data) {
          data = JSON.parse(data)
        }
        if (data.code == 200) {
          let fileList = [
            {
              url: data.data.fileUrl,
              thumb: data.data.fileUrl,
              status: 'success',
              isImage: true,
              name: 'img',
              id: '1',
              type: 'image'
            }
          ]
          if (_this.data.from == 'qrcode') {
            _this.setData({
              fileListQr: fileList
            })
          } else {
            _this.setData({
              fileList: fileList
            })
          }
        }
      },
      fail(err) {
        console.log(err)
      }
    })
  },

  afterRead(event) {
    const { file } = event.detail
    const image = file.tempFilePath
    this.setData({
      from: 'person'
    })
    wx.navigateTo({
      url:
        '/packageMy/croper/croper?imgSrc=' +
        image +
        '&size=' +
        JSON.stringify(this.data.size)
    })
  },
  afterReadQr(event) {
    const { file } = event.detail
    const image = file.tempFilePath
    this.setData({
      from: 'qrcode'
    })
    wx.navigateTo({
      url:
        '/packageMy/croper/croper?imgSrc=' +
        image +
        '&size=' +
        JSON.stringify(this.data.size)
    })
  },

  deleteImg() {
    this.setData({
      fileList: [],
      imgUrl: ''
    })
  },

  deleteImgQr() {
    this.setData({
      fileListQr: [],
      qrCode: ''
    })
  },

  toTemplate() {
    wx.navigateTo({
      url:
        '/packagePlan/imgTemplate/imgTemplate?from=' +
        'homepage'
    })
  },

  submit() {
    if (this.data.nickName.length <= 0) {
      wx.showToast({
        title: '请填写昵称',
        icon: 'none'
      })
      return
    }
    if (this.data.realName.length <= 0) {
      wx.showToast({
        title: '请填写真实姓名',
        icon: 'none'
      })
      return
    }
    if (this.data.idCard.length <= 0) {
      wx.showToast({
        title: '请填写身份证号',
        icon: 'none'
      })
      return
    }
    if (this.data.phone.length <= 0) {
      wx.showToast({
        title: '请填写电话',
        icon: 'none'
      })
      return
    }
    if (this.data.address.length <= 0) {
      wx.showToast({
        title: '请填写地址',
        icon: 'none'
      })
      return
    }
    if (this.data.gender.length <= 0) {
      wx.showToast({
        title: '请选择性别',
        icon: 'none'
      })
      return
    }
    // 防止当fileList为空数组时报错
    try {
      this.setData({
        groupLeaderShowPic: this.data.fileList[0]
          .url
      })
    } catch (error) {
      wx.showToast({
        title: '请上传个人展示',
        icon: 'none'
      })
      return
    }
    if (
      this.data.groupLeaderShowPic.length <= 0
    ) {
      wx.showToast({
        title: '请上传个人展示',
        icon: 'none'
      })
      return
    }
    try {
      this.setData({
        qrCode: this.data.fileListQr[0].url
      })
    } catch (error) {
      wx.showToast({
        title: '请上传个人二维码',
        icon: 'none'
      })
      return
    }
    if (this.data.qrCode.length <= 0) {
      wx.showToast({
        title: '请上传个人二维码',
        icon: 'none'
      })
      return
    }

    request({
      url: '/mini/api/mine/saveUserInfo',
      method: 'POST',
      data: {
        address: this.data.address,
        latitude: this.data.latitude,
        longitude: this.data.longitude,
        avatar: null,
        community: this.data.community,
        gender: this.data.gender,
        groupLeaderShowPic: this.data
          .groupLeaderShowPic,
        idCard: this.data.idCard,
        nickName: this.data.nickName,
        phone: this.data.phone,
        realName: this.data.realName,
        qrCode: this.data.qrCode
      }
    }).then((resdata) => {
      console.log(resdata)
      if (resdata.code == 200) {
        wx.showToast({
          title: '操作成功',
          icon: 'none'
        })
        setTimeout(() => {
          wx.navigateBack()
        }, 200)
      } else {
        wx.showToast({
          title: resdata.message,
          icon: 'none'
        })
      }
    })
  },

  getLocation() {
    let _this = this
    wx.chooseLocation({
      type: 'wgs84',
      success(res) {
        _this.setData({
          address: res.address,
          latitude: res.latitude,
          longitude: res.longitude
        })
      },
      fail(err) {
        console.log(err)
      }
    })
  },

  getPhoneNumber(e) {
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      request({
        url: '/mini/api/mine/getMobileByCode',
        method: 'POST',
        data: {
          code: e.detail.code
        }
      }).then((resdata) => {
        if (resdata.code == 200) {
          this.setData({
            phone: resdata.data
          })
        } else {
          wx.showToast({
            title: resdata.message,
            icon: 'none'
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (app.globalData.imgSrc.length > 0) {
      this.uploadImg(app.globalData.imgSrc)
      app.globalData.imgSrc = ''
    }
    if (this.data.imgUrl.length > 0) {
      let fileList = [
        {
          url: this.data.imgUrl,
          thumb: this.data.imgUrl,
          status: 'success',
          isImage: true,
          name: 'img',
          id: '1',
          type: 'image'
        }
      ]
      this.setData({
        fileList: fileList
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
})
